package com.rst.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rst.dao.StudentDAO;
import com.rst.model.Section;
import com.rst.model.Student;
import com.rst.model.StudentCategory;
import com.rst.model.UserDetailsDTO;
import com.rst.view.AdmissionFormView;

@Service
public class StudentService {

	@Autowired
	private StudentDAO studentDAO;

	private Logger logger = Logger.getLogger(StudentService.class);
	
	public void update(StudentCategory category, Long categoryId) {
		category.setId(categoryId);
		studentDAO.udateStudentCategory(category);		
	}

	public Long saveCategory(StudentCategory category) {
		return studentDAO.saveCategory(category);		
	}

	public StudentCategory getStudentCategoryById(Long categoryId) {
		return studentDAO.getStudentCategoryById(categoryId);
	}

	public List<Section> getClassAndSections() {
		return studentDAO.getClassAndSections();
	}

	public List<StudentCategory> getStudentCategory() {
		return studentDAO.getStudentCategory();
	}

	public Long saveAddmissionForm(AdmissionFormView form) {
	    Object[] obj = proccessUserDetail(form);
	    proccessStudentDetail(form , obj);
		return 1l;
	}

	private void proccessStudentDetail(AdmissionFormView form, Object[] obj) {
		Student student = new Student();
		student.setAdmissionNo((Long) obj[0]);
		student.setUserId((String) obj[1]);
		student.setClassRollNo(form.getClassRollNo());
		student.setSectionId(form.getSectionId());
		student.setStatus(Student.ACTIVE);
		student.setStudentCategoryId(form.getStudentCategoryId());
		student.setAdmissionDate(form.getAdmissionDate());
		student.setCreatedAt(new Date());
		student.setUpdatedAt(new Date());
	    studentDAO.saveStudent(student);
	}

	private Object[] proccessUserDetail(AdmissionFormView form) {
		UserDetailsDTO userDetails = new UserDetailsDTO();
		Object[] obj = new Object[2];
		
		//Long admissionNo = getAdmissionNo();
		userDetails.setUsername("std"+form.getAdmissionNo());           // auto generated  to discuss
		userDetails.setPassword("pass"+form.getAdmissionNo());          // auto generated  to discuss
		userDetails.setCreatedDate(new Date());
		userDetails.setEmailId(form.getEmailId());
		userDetails.setFirstName(form.getUserDisplayNameFirst());
		userDetails.setLastName(form.getUserDisplayNameLast());
		userDetails.setEnabled(UserDetailsDTO.ENABLE);
		userDetails.setFatherName(form.getFatherName());
		userDetails.setMotherName(form.getMotherName());
		userDetails.setHusbandName(form.getHusbandName());
		userDetails.setPhone(form.getPhone());
		userDetails.setPin(form.getPin());
		userDetails.setPhotoUrl(form.getPhotoUrl());
		userDetails.setThumbnailPhotoUrl(form.getThumbnailPhotoUrl());
		userDetails.setCityId(form.getCityId());
		userDetails.setGender(form.getGender());
		userDetails.setDob(form.getDob());
		userDetails.setBloodGroup(form.getBloodGroup());
		userDetails.setStrCreatedAuthor("admin");  // need to get the current role from session  
		userDetails.setAccountNonExpired(true);
		userDetails.setAccountNonLocked(true);
		userDetails.setCredentialsNonExpired(true);
		userDetails.setAddress(form.getAddress1() + form.getAddress2());
		
		obj[0] = form.getAdmissionNo();
		obj[1] = userDetails.getUsername();
		
	    studentDAO.saveUser(userDetails);
		return obj;

	}

	public Long getAdmissionNo() {
		Long admissionNo = null;		
		try {
			Student st  = studentDAO.getAdmissionNo();
			if(st.getAdmissionNo() != null){
				Long adno = st.getAdmissionNo() ;
				admissionNo =  ++ adno;
			}
		} catch (Exception e) {
			admissionNo = 1l;
		}
		return admissionNo;
	}

	public List<AdmissionFormView> getAdmissionFormData(InputStream stream)
	  {
	    int rowCount = 0;
	    int emptyRowEncountered = 0;

	    List<AdmissionFormView> studentList = new ArrayList<AdmissionFormView>();
	    try {
	      HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(stream));

	      HSSFSheet sheet1 = wb.getSheetAt(0);
	      for (org.apache.poi.ss.usermodel.Row row : sheet1)
	      {
	        if (row == null) break;
	        if (row.getRowNum() > 0)
	        {
	        	AdmissionFormView student = new AdmissionFormView();
	          for (int counter = 1; counter < 12; counter++)
	          {
	            if (counter >= 12) {
	              break;
	            }
	            Cell cell = row.getCell(counter);
	            if ((cell != null) || (counter <= 0))
	            {
	              switch (counter)
	              {
	              case 1:
		                if ((cell != null))
		                {
		                  student.setAdmissionNo((new Double(cell.getNumericCellValue())).longValue());  
		                }break;
	              case 2:
	                if ((cell != null) && (cell.getCellType() == 1))
	                {
	                  student.setUserDisplayNameFirst(cell.getStringCellValue());
	                }break;
	              case 3:
	                if ((cell != null) && (cell.getCellType() == 1))
	                {
	                  student.setUserDisplayNameLast(cell.getStringCellValue());
	                }break;
	              case 4:
	                if ((cell != null) && (cell.getCellType() == 1) && (cell.getCellType() != 3))
	                {
	                  student.setEmailId(cell.getStringCellValue());
	                }break;
	              case 5:
		                if ((cell != null) && (cell.getCellType() == 1))
		                {
		                  student.setDob(stringToDate(cell.getStringCellValue()));
		                }break;

	              case 6:
	                if ((cell != null) && (cell.getCellType() == 1))
	                {
	                  student.setGender(cell.getStringCellValue());
	                }break;
	              
	              case 7:
		                if ((cell != null) && (cell.getCellType() == 0))
		                {
		                  student.setClassRollNo((new Double(cell.getNumericCellValue())).longValue());
		                }break;
		              
	              case 8:
		                if ((cell != null) && (cell.getCellType() == 0))
		                {
		                  student.setSectionId((new Double(cell.getNumericCellValue())).longValue());
		                }break;
		              
	              case 9:
		                if ((cell != null) && (cell.getCellType() == 0))
		                {
		                  student.setStudentCategoryId((new Double(cell.getNumericCellValue())).longValue());
		                }break;
		                
	              case 10:
	                if (cell != null)
	                {
	                  if (cell.getCellType() == 0)
	                    student.setPhone(cell.getNumericCellValue()+"");   // need to change and convert in string
	                }
	                break;
	              }
	            }
	          }
	          if ((student.getEmailId() == null) || (student.getEmailId().trim().length() == 0)) {
	            emptyRowEncountered++;
	          }
	          else
	          {
	            if (emptyRowEncountered > 5)
	            {
	              break;
	            }
	            studentList.add(student);
	            rowCount++;
	          }
	        }
	      } } catch (IOException e) {logger.error("Error in Reading Excel Data. Total rows read =  " + rowCount + "\n" + e); }

	    return studentList;
	  }

     private Date stringToDate(String strDate){
    	 SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy");
    		try {
    	 
    			return formatter.parse(strDate);    			    	 
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
			return null; 
    	 
     }

	public void saveBulkAddmissionForm(List<AdmissionFormView> studentList) {
		for (AdmissionFormView form : studentList) {
			saveAddmissionForm(form);
		}
		
	}

	public List<Student> getStudentsBySectionId(Long sectionId) {
		return studentDAO.getStudentsBySectionId(sectionId);
	}


	public List<UserDetailsDTO> getStudentsByName(String name) {
		return studentDAO.getStudentsByName(name);
	}

	public List<StudentCategory> getCategoryList() {
		return studentDAO.getStudentCategory();
	}

	public String deleteStudentCategory(Long categoryId) {
		StudentCategory  category = studentDAO.getStudentCategoryById(categoryId);
		category.setStatus(StudentCategory.INACTIVE);
		studentDAO.udateStudentCategory(category);	
		return "success";
	}

	public String processStudentList(List<Student> studentsList , HttpServletRequest req) {		
		String ajaxString = "";
        if(studentsList!= null && studentsList.size()>0){
        	ajaxString = ajaxString + "<div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>Student List</h3></div><div class='panel-body'>"
        			+ "<div class='table-responsive'><table class='table table-striped table-bordered table-hover'><thead><tr><th><span>Sr No</span></th><th><span>Name</span></th><th><span>Adm No</span></th> </tr></thead><tbody>";
        	int srNo = 1;
        	for (Student student : studentsList) {
        		ajaxString = ajaxString + "<tr><td>"+ srNo++ +"</td>"; 
        		ajaxString = ajaxString + "<td>"+ student.getUserDetails().getFirstName()+" " + student.getUserDetails().getLastName()  +"</td>"; 
        		ajaxString = ajaxString + "<td>"+ student.getAdmissionNo()  +"</td>"; 
        		ajaxString = ajaxString+ "<td>";	
        		ajaxString = ajaxString+ "<a href="+req.getContextPath()+"/studentProfile.htm?id="+student.getId()+"><button class='btn btn-primary btn-xs' type='button'>View Profile</button></a>";
                ajaxString = ajaxString+ "</td></tr>";
			}
        	ajaxString = ajaxString + "</tbody></table></div></div></div>";
        }else{
        	ajaxString = ajaxString + "empty";
        }
		return ajaxString;
	} 

	public Student getStudentByStudentId(Long studentId) {
		return studentDAO.getStudentByStudentId(studentId);
	}

	public AdmissionFormView getAdmissionFormByAdmNo(Long admissionNo) {
		   AdmissionFormView admissionForm =  getAdmissionForm(admissionNo);
		   return admissionForm;
	}

	private AdmissionFormView getAdmissionForm(Long admissionNo) {
		Student student  = studentDAO.getStudentByAdmNo(admissionNo);
		AdmissionFormView form = new AdmissionFormView();		
		
		form.setEmailId(student.getUserDetails().getEmailId());
		form.setUserDisplayNameFirst(student.getUserDetails().getFirstName());
		form.setUserDisplayNameLast(student.getUserDetails().getLastName());
		form.setPhone(student.getUserDetails().getPhone());
		form.setPin(student.getUserDetails().getPin());
		form.setPhotoUrl(student.getUserDetails().getPhotoUrl());
		form.setThumbnailPhotoUrl(student.getUserDetails().getThumbnailPhotoUrl());
		form.setCityId(student.getUserDetails().getCityId());
		form.setGender(student.getUserDetails().getGender());
		form.setDob(student.getUserDetails().getDob());
		form.setBloodGroup(student.getUserDetails().getBloodGroup());
		form.setAddress1(student.getUserDetails().getAddress());
		return form;
	}

	

} 

